/**
 * @description Ccay XSimpleFlow 简易流程图
 */
(function(XSimpleFlow){
	// set defalut config
	var config = {
		type : "flow", // 默认为简易流程图
		dateName : "date", // 默认日期字段名为date
		//url:"services/ccay/htmlarea/query/list/{0}/{1}" // 富文本的url {0}:类型 {1}：名称
		url:"services/ccay/workflow/log/htmlareaTmpl/{0}/{1}" //暂时使用工作流的历史记录重新封装的查询,无权限问题
	};
	//define control flow
	var flow = {
		init:function(pic, op){
			pic.dom.addClass("ccay-simpleflow " + (op.css || ""));
		},
		build:function(pic, op){
			ccaySimpleFlow.buildBody(pic, op);
		},
		bindEvent:function(pic, op){
			// 悬停事件
			ccaySimpleFlow.bindHoverEvent(pic, op);
			// 人员点击事件
			ccaySimpleFlow.bindUserEvent(pic.dom, op);
		    // 有滚动条时绑定鼠标滚轮事件
			/*var containerWidth = pic.dom.find(".ccay-simpleflow-container").width(),
				displayWidth = pic.dom.width();
			if(containerWidth > displayWidth){
				pic.dom.bind("mousewheel",function(e){
					var currLeft = $(this).scrollLeft();
					// > 0 往上滚
					if(e.originalEvent.wheelDelta > 0){
						$(this).scrollLeft(currLeft - 100);
					}else{  // < 0 往下滚
						$(this).scrollLeft(currLeft + 100);
					}
					// 最顶端和最底端后则触发浏览器的滚动
					if(currLeft == 0 || currLeft + displayWidth == containerWidth){
						return true;
					}else{
						return false;
					}
				})
			}*/
		}
	};
	//define control manager
	var manager = {};
	//create XControl
	var XSimpleFlow = Ccay.UI.XControl("XSimpleFlow", flow, config, manager);
	// create jquery plugin
	$.fn.ccaySimpleFlow = function(op){
		return new XSimpleFlow(this, op);
	};
	var ccaySimpleFlow = {
		// 构建主体
		buildBody:function(pic, op){
			if(op.templateName || op.template){
				var dateName = op.dateName,
					tempList = [],
					container = $.create("div", "ccay-simpleflow-container");
				pic.dom.append(container);
				for(var i = 0, node; node = op.nodes[i]; i++){
					// 时间转换
					node[dateName] && node[dateName].length > 10 && (node[dateName] = Ccay.Format.toDateTimeStr(node[dateName]));
					// 显示名
					if(node.displayName){
						node.name = $i18n(node.displayName);
					}
					// 节点
					tempList.push("<div class='ccay-simpleflow-node'></div>");
					// 线条
					op.type != "timeline" && op.nodes[i+1] && tempList.push("<div class='ccay-simpleflow-process'></div>");
					// 当前处理节点的序号
					node.status == "doing" && (op.__activeNodeNo = i);
				}
				container.append(tempList.join(""));
				// 设置节点,样式等
				ccaySimpleFlow.buildNodes(pic, op);
				ccaySimpleFlow.buildDomStyle(pic, op);
			}
		},
		// 模板构建节点
		buildNodes : function(pic, op){
			var nodes = $(".ccay-simpleflow-node", pic.dom),
				process = $(".ccay-simpleflow-process", pic.dom),
				nodesLength = nodes.length,
				currentNode,
				hasActiveNode = op.__activeNodeNo != null;
			// process
			process.slice(0, hasActiveNode ? op.__activeNodeNo : nodesLength).addClass("simpleflow-node-ready");
			// 如果指定模板名称则根据名称查找富文本模板
			op.templateName && this.getTemplateContent(op);
			// nodes
			$.each(nodes, function(i, node){
				currentNode = $(node); 
				currentNode.ccayTemplate({tmpl:op.template}, op.nodes[i]);
				// 单个节点的css
				op.nodes[i].css &&　currentNode.addClass(op.nodes[i].css);
				// 存在当前处理节点按状态处理,否则全部是已处理状态
				if(op.type != "timeline"){
					// 首尾节点
					i == 0 && currentNode.addClass("simpleflow-node-start");
					i == nodesLength - 1 && currentNode.addClass("simpleflow-node-end");
					if(hasActiveNode){
						if(i == op.__activeNodeNo){
							currentNode.addClass("simpleflow-node-doing").find(".simpleflow-node-time").hide();
						}else if(i < op.__activeNodeNo){
							currentNode.addClass("simpleflow-node-ready");
						}else{
							currentNode.find(".simpleflow-node-handler, .simpleflow-node-time").hide();
						}
					}else{
						currentNode.addClass("simpleflow-node-ready");
					}
				}
			})
		},
		// 构建高度,宽度,滚动条位置样式
		buildDomStyle : function(pic, op){
			if(op.type != "timeline"){
				// 节点和线条的宽度
				var firstNode =  $(".ccay-simpleflow-node:first", pic.dom),
					nodeWidth = firstNode.outerWidth(true),
					processWidth = $(".ccay-simpleflow-process:first", pic.dom).outerWidth(true),
					// 节点加上线条的宽度
					nodeSumWidth = nodeWidth + processWidth,
					// 总长度,节点和线条成对出现，但最后少一条线
					containerWidth = op.nodes.length * nodeSumWidth - processWidth,
					activeNodeNo = op.__activeNodeNo, dom = pic.dom;
				setTimeout(function(){
					dom.height(firstNode.find("ul:first").height());
					dom.find(".ccay-simpleflow-container").width(containerWidth);
					// // 当有了滚动条后再做滚动条位置处理无当前处理节点
					if(containerWidth > dom.width()){
						//无当前处理节点,移到最右边
						if(activeNodeNo == null){
							dom.scrollLeft(containerWidth);
						// 当第二个节点之后的,移动相应宽度
						}else if(activeNodeNo > 2){
							dom.scrollLeft((activeNodeNo - 2) * nodeSumWidth);
						}
					}
				},100);
			}else{
				var nodes = $(".ccay-simpleflow-node", pic.dom);
				$.each(nodes, function(i, node){
					// 高度设置
					$(node).height($(node).find(".timeline-right .timeline-content").height() + 30);
				})
			}
		},
		// 指定内容区悬停事件
		bindHoverEvent : function(pic, op){
			// 指定class为simpleflow-node-content的元素绑定鼠标悬停事件
			var popBody = pic.dom.find(".simpleflow-node-content");
			popBody.children().mouseover(
				function(){
					var popDiv = $(this).parent(),
						popDivChild = popDiv.children();
					if(popDivChild.length){
						var cloneArea = popDiv.clone(),
							picArea = $(".ccay-simpleflow-user");
						if(!picArea.length){
							picArea = $.create("div", "ccay-simpleflow-user hide");
							picArea.mouseleave(function(){
								$(this).hide();
							}).mouseover(function(){
								$(this).show();
							});
						};
						$(document.body).append(picArea.html($("<ul></ul>").append(cloneArea)));
						// 显示人员区
						var firstChild = popDiv.find(":first-child");
						picArea.css({
							// 除去padding宽度
							top: firstChild.offset().top - 3,
							left:firstChild.offset().left - 6 
						}).show(100);
						ccaySimpleFlow.bindUserEvent(picArea, op);
					}
			}).mouseout(
				function(){
					$(".ccay-simpleflow-user").hide();
			});
		},
		// 人员链接点击事件
		bindUserEvent : function(container, op){
			$(".handler-user", container).on("click", function(e){
				var me = $(this);
				if(me.hasClass("group")){
					Ccay.workflow.groupPopup(me.text(), op.processInstanceId);
				}else{
					Ccay.Component.popUserInfo(me.text());
				}
			});
		},
		// timeline 排序处理
		buildTimelineNodes:function(op){
			var dateName = op.dateName,
				newNodes = [],
				dateTmp,
				uniqueKeyDate,
				fullDateObj = {};
			$.each(op.nodes, function(i, node){
				var tmpNode={};
					dateTmp = node[dateName].toDate().getUTCTime(); 
				// 分组主键，自定义格式sortFormat
				uniqueKeyDate = Ccay.Format.toDateStr(dateTmp, op.sortFormat); 
				// 添加分类节点
				if(!fullDateObj[uniqueKeyDate]){
					fullDateObj[uniqueKeyDate] = true;
					tmpNode[dateName] = uniqueKeyDate;
					tmpNode.css = "simpleflow-sortnode"; 
					newNodes.push(tmpNode);
				}
				node.css || (node.css = "");
				// 节点时间，自定义格式dateFormat
				node[dateName] = Ccay.Format.toDateStr(dateTmp, op.dateFormat); 
				newNodes.push(node);
			});
			op.nodes = newNodes;
		},
		// 通过模板名称获得模板内容
		getTemplateContent : function(op){
			Ccay.doGet({
			    async:false,// 同步
			    url:op.url.formatValue("SimpleDiagramTemplate", op.templateName),
			    data:"",
			    success : function(data){
			    	return op.template = data.content;
			    },
			    loading : false
			});
		}
	};
	
	// 时间轴插件
	Ccay.UI.XControl.addPlugin("XSimpleFlow", "timeline", {
	    preInit : function( pic, op ) {
	    	if(op.type == "timeline"){
	    		op.css = "ccay-timeline";
	    		// 分段 主键格式化
	    		op.sortFormat || (op.sortFormat = Ccay.Config.Format.date);
	    		// 展示时间  格式化
	    		op.dateFormat || (op.dateFormat = "hh:mm");
		    	// 节点先排序
		    	Ccay.DataHelper.sort(op.dateName, op.asc ? "asc" : "desc", op.nodes);
		    	// 构造节点
		    	ccaySimpleFlow.buildTimelineNodes(op);
	    	}
	    },
	    build:function(pic, op){
	    	if(op.type == "timeline"){
	    		op.handler.complete.add(function(){
		    		var mainNode,
		    			nextNode,
		    			toggleObj = pic.dom.find(".simpleflow-sortnode .timeline-toggle");
			    	toggleObj.on("click", function(){
			    		
			    		$(this).toggleClass("collapse");
			    		
			    		// 组名节点
			    		mainNode = $(this).closest(".ccay-simpleflow-node.simpleflow-sortnode");
			    		// 隐藏该组下的子节点
			    		nextNode = mainNode.next();
			    		while(nextNode.length && !nextNode.hasClass("simpleflow-sortnode")){
			    			nextNode.toggle("fast");
			    			nextNode = nextNode.next();
			    		}
			    	})
	    		})
	    	}
	    }
	 });
	
})(Ccay.UI.XSimpleFlow);